<template>
  <div class="container">
    <!-- 上传文件 -->
    <div class="text-center upload-box">
      <div>
        <el-upload
          ref="rebateUpload"
          class="upload-demo"
          drag
          :action="upload"
          name="excel"
          :data="uploadData"
          :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          v-show="isShowUpload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t("page.drop") }}，<em>{{ $t("page.click") }}</em>
          </div>
        </el-upload>

        <div class="reset-back" v-if="isShowStepOne">
          <div class="link" @click="changLogData">{{ $t("page.modData") }}</div>
          <span class="link" @click="handleRemove">{{
            $t("page.emptyData")
          }}</span>
        </div>

        <div class="upload-name-box">
          <div class="upload-name" v-show="isShowUploadtxt">
            {{ uploadFile.name }}
            <el-button type="text" @click="handleRemove()">x</el-button>
          </div>
          <el-progress
            :percentage="percentage"
            :color="customColor"
            v-show="isShowPer"
          ></el-progress>
        </div>
      </div>
    </div>
    <!-- 上传文件-done -->

    <div class="container-body" v-if="isShowStepOne">
      <!-- 核酸检测结果 -->
      <div class="wave">
        <template v-for="(inner, key, index) in result2InnerGraph">
          <div class="graph">
            <div class="title-space">
              <span>
                {{ key }}
                {{ $t("page.testResults") }}
                <!-- -
                {{$t('page.positive')}} -->
              </span>
            </div>
            <div class="result-light">
              <template v-for="(v, i) in inner">
                <!-- <div :key="i" class="result-item"
                  v-if="v ===1">
                  {{waveName[i]}}
                </div> -->
                <div
                  class="result-item"
                  :style="{
                    border: `1px solid ${v === 1 ? 'red' : 'green'}`,
                    'background-color': `${v === 1 ? 'red' : 'green'}`,
                  }"
                >
                  {{ waveName[i] }}
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>

      <template v-for="(waveLengthV, waveLengthIndex) in waveLength">
        <div v-if="models[0].checked" :key="waveLengthIndex">
          <div class="title-space">
            <span>{{ waveLengthV }}-{{ $t("page.ODvalue") }}：</span>
          </div>
          <div
            v-for="(listItem, listIndex) in originalData"
            :key="listIndex"
            class="overflow"
          >
            <template v-if="listIndex === waveLengthIndex">
              <table id="table-1">
                <tr v-for="(table, key, index) in listItem" :key="index">
                  <td>
                    <span v-if="key !== 'time'">
                      {{ waveName[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      <!-- {{$t('page.hole')}} -->
                      {{ $t("page.hole") }}
                    </span>
                  </td>
                  <td>
                    <span v-if="key !== 'time'">
                      {{ holeLabel[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      <!-- {{$t('page.number')}} -->
                      {{ $t("page.number") }}
                    </span>
                  </td>
                  <td>
                    <span v-if="key !== 'time'">
                      {{ virusLabel[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      {{ $t("page.label") }}({{ unit }})
                    </span>
                  </td>
                  <td v-for="(iTable, i) in table" :key="i">
                    <span v-if="key !== 'time'">{{ iTable }}</span>
                    <span class="color-000" v-else>{{ iTable + "m" }}</span>
                  </td>
                </tr>
              </table>
            </template>
          </div>
        </div>
        <div v-if="models[1].checked" :key="waveLengthIndex">
          <div class="title-space">
            <span>{{ waveLengthV }}-{{ $t("page.ODrate") }}（%）：</span>
          </div>
          <div
            v-for="(listItem, listIndex) in originalDataRate"
            class="overflow"
            :key="listIndex"
          >
            <template v-if="listIndex === waveLengthIndex">
              <table id="table-1">
                <tr v-for="(table, key, index) in listItem" :key="index">
                  <td>
                    <span v-if="key !== 'time'">
                      {{ waveName[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      {{ $t("page.hole") }}
                    </span>
                  </td>
                  <td>
                    <span v-if="key !== 'time'">
                      {{ holeLabel[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      {{ $t("page.number") }}
                    </span>
                  </td>
                  <td>
                    <span v-if="key !== 'time'">
                      {{ virusLabel[index - 1] }}
                    </span>
                    <span class="color-000" v-else>
                      {{ $t("page.label") }}({{ unit }})
                    </span>
                  </td>
                  <td v-for="(iTable, i) in table" :key="i">
                    <span v-if="key !== 'time'">{{ iTable }}</span>
                    <span class="color-000" v-else>{{ iTable + "m" }}</span>
                  </td>
                </tr>
              </table>
            </template>
          </div>

          <div class="space text-center">
            <template v-for="(chart, index) in allStepOneCharts">
              <div :key="index" class="chart" v-if="index === waveLengthIndex">
                <wave-chart
                  :id="'waveStepOne1' + index"
                  :data="chart"
                ></wave-chart>
              </div>
            </template>
          </div>
        </div>
      </template>

      <!-- 计算结果 -->
      <div class="title-space">
        <h3>{{ $t("page.calResultes") }}：</h3>
        <el-button type="text" @click="downloadExl()" size="mini">
          {{ $t("page.export") }}
        </el-button>
      </div>

      <div>
        <div class="wave">
          <div class="overflow" v-if="models[2].checked">
            <!-- 波长差值表格 -->
            <table id="table-1">
              <tr>
                <td class="color-000">
                  {{ $t("page.waveDiff") }}
                </td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in waveLengthDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ waveName[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <tr>
                <td class="color-000">
                  {{ $t("page.number") }}
                </td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in waveLengthDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ holeLabel[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <tr>
                <td class="color-000">
                  {{ $t("page.label") }}
                </td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in waveLengthDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ virusLabel[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <template v-for="(waveItem, waveKey) in waveLengthDiff">
                <tr>
                  <td>
                    {{ waveKey }}
                  </td>
                  <td v-for="(v, i) in waveLengthDiff[waveKey]" :key="i">
                    {{ v }}
                  </td>
                </tr>
              </template>
            </table>
          </div>

          <div class="overflow" v-if="models[4].checked">
            <!-- 归零处理表格 -->
            <table id="table-1">
              <tr>
                <td class="color-000">
                  {{ $t("page.ratioText") }}
                </td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in innerControlDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ waveName[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <tr>
                <td class="color-000">
                  {{ $t("page.number") }}
                </td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in innerControlDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ holeLabel[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <tr>
                <td class="color-000">{{ $t("page.label") }}({{ unit }})</td>
                <template
                  v-for="(waveItem, waveKey, waveIndex) in innerControlDiff"
                >
                  <template v-for="(wave, wIndex) in waveItem">
                    <td v-if="waveIndex === 0" :key="wIndex">
                      <span>
                        {{ virusLabel[wIndex] }}
                      </span>
                    </td>
                  </template>
                </template>
              </tr>
              <template v-for="(waveItem, waveKey) in innerControlDiff">
                <tr>
                  <td>
                    {{ waveKey }}
                  </td>
                  <td v-for="(v, i) in innerControlDiff[waveKey]" :key="i">
                    {{ v }}
                  </td>
                </tr>
              </template>
            </table>
          </div>
          <template v-for="(chart, index) in waveCharts">
            <template v-if="models[2].checked">
              <wave-chart
                :key="index"
                :id="'waveRate1' + index"
                :data="chart"
              ></wave-chart>
            </template>
          </template>

          <!-- 567-456归零处理 -->
          <template v-for="(chart, index) in innerCharts">
            <template v-if="models[4].checked">
              <wave-chart
                :key="index"
                :id="'innerCharts1' + index"
                :data="chart"
              ></wave-chart>
            </template>
          </template>
        </div>
      </div>

      <!-- 没有作用  -->
      <div v-if="models[3].checked">
        <template v-for="(chart, index) in allwaveLengthDiffSingleCharts">
          <wave-chart
            :id="'waveSingle1' + index"
            :data="chart"
          ></wave-chart>
        </template>
      </div>

      <div class="space text-center"></div>
    </div>
    <!-- 核酸检测结果-done -->

    <!------------------ 截图曲线 -->
    <div class="m-top-fff" v-if="showScreenshotsImg">
      <template v-for="(chart, index) in allStepOneCharts">
        <wave-chart
          :id="'waveStepOne' + index"
          :data="chart"
          @shotImg="shotImg"
        ></wave-chart>
      </template>

      <template v-for="(chart, index) in waveCharts">
        <wave-chart
          :id="'waveRate' + index"
          :data="chart"
          @shotImg="shotImg"
        ></wave-chart>
      </template>
      <template v-for="(chart, index) in allwaveLengthDiffSingleCharts">
        <wave-chart
          :id="'waveSingle' + index"
          :data="chart"
          @shotImg="shotImg"
        ></wave-chart>
      </template>
      <template v-for="(chart, index) in innerCharts">
        <wave-chart
          :id="'innerCharts' + index"
          :data="chart"
          @shotImg="shotImg"
        ></wave-chart>
      </template>
    </div>

    <!-- 弹窗部分 -->
    <el-dialog
      :visible.sync="isShowInputLog"
      :close-on-click-modal="false"
      width="90%"
      top="5%"
      center
    >
      <div>
        <div class="title-space">
          <span>{{ $t("page.unit") }}</span>
        </div>
        <el-radio-group v-model="unit">
          <el-radio
            :label="item"
            v-for="(item, index) in unitOption"
            :key="index"
          ></el-radio>
        </el-radio-group>
        <div class="title-space">
          <span>{{ $t("page.module") }}</span>
        </div>
        <template v-for="(v, i) in models">
          <el-checkbox v-model="v.checked" :key="i" v-if="v.show">{{
            $t("page.models" + i)
          }}</el-checkbox>
        </template>

        <div class="title-space">
          <span>{{ waveName.length }}{{ $t("page.hole") }}</span>
        </div>
        <div class="overflow">
          <table id="table-1">
            <tr>
              <td width="30">
                {{ $t("page.hole") }}
              </td>
              <td v-for="(table, index) in waveName" :key="index" width="50">
                {{ table }}
              </td>
            </tr>
            <tr>
              <td width="30">{{ $t("page.label") }}({{ unit }})</td>
              <td v-for="(table, index) in waveName" :key="index">
                <el-input type="number" v-model="beforeLable[index]"></el-input>
              </td>
            </tr>
            <tr>
              <td width="30">
                {{ $t("page.number") }}
              </td>
              <td v-for="(table, index) in waveName" :key="index">
                <el-input
                  type="number"
                  v-model="holeLabel[index]"
                  @input="inputTags(index)"
                ></el-input>
              </td>
            </tr>
          </table>
        </div>

        <div class="addcontrast-item">
          <div class="title-space ">{{ $t("page.negativeControl") }}：</div>
          <el-select v-model="innerControl[0]" placeholder="">
            <el-option
              v-for="item in waveName"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <div style="margin-left:20px;" class="title-space ">
            {{ $t("page.positiveControl") }}：
          </div>
          <el-select v-model="innerControl[1]" placeholder="">
            <el-option
              v-for="item in waveName"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </div>

        <!-- cutooff值 -->
        <el-row style="margin-top:20px;">
          <el-col :span="8">
            <div class="addcontrast-item">
              <div class="title-space ">
                {{ $t("page.cutoffCoefficient") }}：
              </div>
              <el-input
                type="input"
                style="width:60px;"
                @keyup.native="
                  cutoffFactor = cutoffFactor.replace(/[^\d || . || -]/g, '')
                "
                v-model="cutoffFactor"
              >
              </el-input>
            </div>
          </el-col>
        </el-row>
        <template>
          <div class="flex-space" style="display: flex;">
            <span class="title-space">{{ $t("page.histogram") }}</span>
            <div>
              <el-button type="primary" @click="addContrastBtn()" size="mini">{{
                $t("page.add")
              }}</el-button>
              <el-button @click="reset()" size="mini">{{
                $t("page.reset")
              }}</el-button>
            </div>
          </div>
          <el-form ref="addContrast" :model="addContrast">
            <el-form-item v-for="(v, i) in addContrast.contrast" :key="i">
              <el-col :span="8" class="addcontrast-item">
                <div class="label">{{ $t("page.length") }} (min)：</div>
                <!-- <el-input v-model="v.minute"
                          class="addcontrast-el-input"
                          placeholder="分钟"></el-input> -->
                <el-select
                  class="select-width"
                  v-model="v.minute"
                  :placeholder="$t('page.min')"
                >
                  <el-option
                    v-for="item in timeList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="16" class="addcontrast-item">
                <div class="label-lang">{{ $t("page.wavelength") }} :</div>
                <el-select
                  class="select-width"
                  v-model="v.startWaveLen"
                  placeholder="起始波长"
                >
                  <el-option
                    v-for="item in waveList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
                <!-- <el-input v-model="v.startWaveLen"
                          class="addcontrast-el-input"
                          placeholder="起始波长"></el-input> -->
                <div class="label">-</div>
                <el-select
                  class="select-width"
                  v-model="v.endWaveLen"
                  placeholder="结束波长"
                >
                  <el-option
                    v-for="item in waveList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
                <!-- <el-input v-model="v.endWaveLen"
                          class="addcontrast-el-input"
                          placeholder="结束波长"></el-input> -->
                <el-button
                  @click.prevent="removeContrastBtn(v)"
                  class="delete"
                  v-if="i !== 0"
                  >{{ $t("page.del") }}</el-button
                >
                <div class="delete" v-else></div>
              </el-col>
            </el-form-item>
          </el-form>
        </template>

        <!-- <template v-if="models[3].checked">
          <div class="title-space flex-space">
            <span>光谱差图</span>
            <div>
              <el-button type="primary"
                         @click="addSingleBtn()"
                         size="mini">添加</el-button>
              <el-button @click="resetSingle()"
                         size="mini">重置</el-button>
            </div>
          </div>

          <el-form ref="addContrast"
                   :model="addContrast">
            <el-form-item v-for="(v, i) in addContrast.single"
                          :key="i">
              <el-col :span="24"
                      class="addcontrast-item">
                <div class="label">起始时长： </div>
                <el-input v-model="v.startMin"
                          class="addcontrast-el-input"
                          placeholder="分钟"></el-input>

                <div class="label">结束时长： </div>
                <el-input v-model="v.endMin"
                          class="addcontrast-el-input"
                          placeholder="分钟"></el-input>
                <el-button @click.prevent="removeSingleBtn(v)"
                           class="delete"
                           v-if="i !== 0">删除</el-button>
                <div class="delete"
                     v-else>
                </div>
              </el-col>
            </el-form-item>
          </el-form>
        </template> -->

        <div class="space text-center">
          <el-button
            type="primary"
            @click="handleCompute()"
            size="small"
            :loading="computeLoading"
            class="btn-submit-color"
          >
            {{ $t("page.submit") }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import waveChart from "@/components/WaveChart";
import { fetchPigStep2, fetchUploadExl } from "@/api/table";
import { setStore, getStore, clearStore } from "@/utils/common";
import { getToken, removeToken } from "@/utils/auth";
import store from "@/store";
import { COLORLIST } from "@/utils/variate";

export default {
  data() {
    return {
      originalData: [],
      originalDataRate: [],
      lightRate: [],
      lightValue: [],
      stepTwoList: [],
      computeLoading: false, //显示计算loading
      computeAllowed: true, //防连点
      isShowInputLog: false, //是否显示公式
      isShowStepOne: false, //是否显示第一步表格
      isShowStepTwo: false, //是否显示第二步表格
      showScreenshotsImg: true, //页面上的曲线隐藏
      isShowUpload: true,
      isShowUploadtxt: false,
      uploadFile: {},
      uploadData: {
        detectType: "4",
      },
      mole: "115207373",
      keyNum: 0, //孔数
      tableTop: [],
      tableSub: [],
      isShowPer: false,
      percentage: 0,
      customColor: "#e6a23c",
      allStepOneCharts: [],
      equation1: "",
      equation2: "",
      equation3: "",
      waveLength: [],
      waveLengthDiff: {},
      waveLengthDiffItem: [],
      waveCharts: [],
      unit: "μg/ml",
      unitOption: ["pg/ml", "ng/ml", "μg/ml", "mg/ml"],
      addContrast: {
        contrast: [],
        single: [
          {
            startMin: "",
            endMin: "",
          },
        ],
      },
      waveName: [],
      beforeLable: [],
      holeLabel: [], //孔标签
      virusLabel: [],
      VirusUnitLabel: [],
      isRepeatSubmit: false,
      models: [
        {
          show: true,
          checked: false,
        },
        {
          show: true,
          checked: false,
        },
        {
          show: true,
          checked: false,
        },
        {
          show: true,
          checked: false,
        },
        {
          show: true,
          checked: true,
        },
      ],
      fullSpectrum: false,
      originalWaveLength: [],
      waveLengthDiffSingle: {},
      allwaveLengthDiffSingleCharts: [],
      result2BarGraph: [], //直方图结果
      result2LightGraph: [], //光谱结果
      resultTitle: [],
      timeList: [],
      waveList: [],
      maxTimeList: "",
      maxWaveList: "",
      minWaveList: "",
      baseStepOne: [],
      innerControl: ["", ""],
      innerControlDiff: {},
      innerCharts: [],
      cutoffFactor: "0.2",
      positiveCrp: "",
      computeCrpValue: {},
      doDownload: false,
      markLineValue: 0, // 标识线的值
    };
  },
  components: {
    waveChart,
  },
  methods: {
    goNext(route, type) {
      if (type === 1) {
        setStore("chartData", this.lightRate);
      }
      this.$router.push({ path: route });
    },
    changLogData() {
      this.isRepeatSubmit = true;
      this.isShowInputLog = true;
      this.doDownload = false;
    },
    beforeUpload(file) {
      this.uploadFile = file;
      this.isShowPer = true;
      this.isShowUpload = false;
      this.isShowUploadtxt = true;
    },
    handleSuccess(file, filelist) {
      // file = {
      const next = 100 - this.percentage;
      this.percentage += next;
      setTimeout(() => {
        this.isShowPer = false;
      }, 1000);
      if (file.status === 200) {
        this.isShowInputLog = true;
        this.fullSpectrum = file.data.fullSpectrum;
        this.models[3].show = file.data.fullSpectrum;
        this.models[3].checked = file.data.fullSpectrum;
        this.waveName = file.data.hole;
        this.timeList = file.data.timeList;
        this.waveList = file.data.waveList;
        this.maxTimeList = this.maxNumber(this.timeList);
        this.minWaveList = this.minNumber(this.waveList);
        this.maxWaveList = this.maxNumber(this.waveList);
        this.addContrast.contrast = [];
        this.addContrastBtn();
        this.beforeLable = [];
        this.holeLabel = [];
        this.waveName.forEach((item) => {
          this.beforeLable.push("");
          this.holeLabel.push("");
        });
        setStore("vuuid", file.data.uuid);
      } else {
        if (file.status === 502) {
          this.$msgbox
            .confirm(this.$t("page.msgBoxLoginOut"), this.$t("page.loginOut"), {
              confirmButtonText: this.$t("page.loginAgin"),
              cancelButtonText: this.$t("page.cancel"),
              type: "warning",
            })
            .then(() => {
              store.dispatch("FedLogOut").then(() => {
                location.reload();
              });
            });
        } else {
          this.$message.error(file.msg);
        }
      }
    },
    inputTags(i) {
      let number = this.holeLabel;
      let numberList = [];
      let afterNumber = 0;
      let beforeNumber = Number(number[i]);
      number.forEach((item, index) => {
        if (index > i) {
          afterNumber = beforeNumber + (index - i);
        } else if (index < i) {
          afterNumber = beforeNumber - (i - index);
        } else if (index === i) {
          afterNumber = beforeNumber;
        }
        numberList.push(afterNumber);
      });
      this.holeLabel = numberList;
    },
    handleError(err) {
      this.$message.error(err);
    },
    returnLabelIndex(label) {
      let selectIndex = "";
      this.waveName.forEach((item, index) => {
        if (label === item) {
          selectIndex = index;
        }
      });
      return selectIndex;
    },
    addContrastBtn() {
      this.addContrast.contrast.push({
        minute: this.maxTimeList,
        startWaveLen: this.maxWaveList,
        endWaveLen: this.minWaveList,
      });
    },
    removeContrastBtn(item) {
      var index = this.addContrast.contrast.indexOf(item);
      if (index !== -1) {
        this.addContrast.contrast.splice(index, 1);
      }
    },
    addSingleBtn() {
      this.addContrast.single.push({
        startMin: "",
        endMin: "",
      });
    },
    removeSingleBtn(item) {
      var index = this.addContrast.single.indexOf(item);
      if (index !== -1) {
        this.addContrast.single.splice(index, 1);
      }
    },
    resetSingle() {
      this.addContrast.single = [
        {
          startMin: "",
          endMin: "",
        },
      ];
    },
    reset() {
      this.addContrast.contrast = [];
      this.addContrast.contrast.push({
        minute: this.maxTimeList,
        startWaveLen: this.maxWaveList,
        endWaveLen: this.minWaveList,
      });
    },
    changePositiveControl(e) {
      const index = this.returnLabelIndex(e);
      this.positiveCrp = this.beforeLable[index];
    },
    async handleCompute() {
      if (!this.unit) {
        this.$message({
          type: "error",
          message: this.$t("page.selectUnit"),
        });
        return;
      } else if (!this.cutoffFactor) {
        this.$message({
          type: "error",
          message: this.$t("page.fillCutoff"),
        });
        return;
      }
      if (!this.innerControl[1]) {
        if (!this.innerControl[0]) {
          this.$message({
            type: "error",
            message: this.$t("page.selectControl"),
          });
          return;
        }
        this.$message({
          type: "error",
          message: this.$t("page.selectControl"),
        });
        return;
      }
      this.computeLoading = true;
      let newSingle = [];
      this.addContrast.single.forEach((item) => {
        const data = {};
        let minItem = item.startMin + ";" + item.endMin;
        data.minute = minItem.toString();
        if (item.startMin) {
          newSingle.push(data);
        }
      });
      let newContrast = [];
      this.addContrast.contrast.forEach((item) => {
        if (item.minute) {
          newContrast.push(item);
        }
      });
      if (this.innerControl[1]) {
        this.changePositiveControl(this.innerControl[1]);
      }
      this.baseStepOne = [];

      let newSubList = [];
      newSubList = newContrast.concat(newSingle);
      let info = null;
      try {
        info = await fetchPigStep2({
          uuid: getStore("vuuid"),
          subList: newSubList,
          unit: this.unit,
          isRepeatSubmit: this.isRepeatSubmit,
          innerControl: this.innerControl,
          cutoffValue: +this.cutoffFactor,
          positiveCrp: this.positiveCrp,
        });
      } catch (e) {
        this.computeLoading = false;
      }
      if (this.isRepeatSubmit) {
        setStore("vuuid", info.data.uuid);
      }
      this.isRepeatSubmit = false;
      this.computeAllowed = true;
      this.computeLoading = false;
      if (info.status === 200) {
        this.waveLengthDiff = info.data.waveLengthDiff;
        // 修改数据参数
        this.innerControlDiff = info.data.result2InnerRate;
        this.markLineValue = info.data.cutoff;
        // this.waveLength = info.data.waveLength
        this.computeCrpValue = info.data.computeCrpValue;
        this.waveLengthDiffSingle = info.data.waveLengthDiffSingle;
        this.showScreenshotsImg = true;
        this.originalWaveLength = info.data.originalWaveLength;
        this.result2BarGraph = info.data.result2BarGraph;
        this.result2InnerGraph = info.data.result2InnerGraph;
        const deOriginalData = info.data.originalData;
        const deOriginalDataRate = info.data.originalDataRate;
        const deArry = info.data.waveLength;

        let trueLabel = [];
        for (let i in this.computeCrpValue) {
          const crpList = this.computeCrpValue[i];
          crpList.forEach((crpValue, crpIndex) => {
            this.beforeLable.forEach((value, index) => {
              if (index === crpIndex) {
                if (value !== "") {
                  trueLabel.push(value);
                } else {
                  trueLabel.push(crpValue);
                }
              }
            });
          });
        }

        let vlabel = [];
        let uvlabel = [];
        trueLabel.forEach((item) => {
          let uItem = "";
          if (item !== "") {
            uItem = item + this.unit;
          } else {
            uItem = item;
          }
          vlabel.push(item);
          uvlabel.push(uItem);
        });
        this.virusLabel = vlabel;
        this.virusUnitLabel = uvlabel;

        // 去重
        let allDeData = [];
        deOriginalData.forEach((i, index) => {
          deOriginalDataRate.forEach((j, indexRate) => {
            deArry.forEach((k, deIndex) => {
              if (index === deIndex) {
                const data = {};
                data.name = k;
                data.arry = i;
                data.arryRate = j;
                allDeData.push(data);
              }
            });
          });
        });
        let allDeAfterData = this.unique(allDeData);
        this.originalData = [];
        this.originalDataRate = [];
        this.waveLength = [];
        allDeAfterData.forEach((item) => {
          this.originalData.push(item.arry);
          this.originalDataRate.push(item.arryRate);
          this.waveLength.push(item.name);
        });
        let barGrapItem = [];
        for (let i in info.data.result2BarGraph) {
          barGrapItem.push(info.data.result2BarGraph[i]);
          this.resultTitle.push(i);
        }
        let lightGrapItem = [];
        info.data.result2LightGraph.forEach((item, index) => {
          const graphItem = [];
          for (let i in item) {
            const data = {};
            data.key = i;
            data.value = item[i];
            graphItem.push(data);
          }
          lightGrapItem.push(graphItem);
        });
        let resultGraphs = [];
        let resultItem = [];
        if (barGrapItem.length > 0 && lightGrapItem.length > 0) {
          lightGrapItem.forEach((lightList, lightIndex) => {
            lightList.forEach((light, index) => {
              if (light.value === 1 || barGrapItem[lightIndex][index] === 1) {
                resultItem.push(light.key);
              }
            });
            resultGraphs.push(resultItem);
          });
        } else if (barGrapItem.length > 0) {
          info.data.hole.forEach((item, index) => {
            if (barGrapItem[0][index] === 1) {
              resultItem.push(item);
            }
          });
          resultGraphs.push(resultItem);
        }

        this.resultGraph = [];
        resultGraphs.forEach((item) => {
          item = [...new Set(item)];
          this.resultGraph.push(item);
        });

        this.drawSingleChart();
        this.drawWaveChart();
        this.drawChart();
        this.drawInnerChart();

        let _this = this;
        _this.$nextTick(() => {
          setTimeout(() => {
            _this.imgUpLoad();
            _this.doDownload = true;
          }, 3000);
        });

        this.isShowInputLog = false;
        this.isShowStepOne = true;
        this.isShowStepTwo = true;
      } else {
        this.$message.error(info.msg);
      }
    },
    async imgUpLoad() {
      await fetchUploadExl({
        uuid: getStore("vuuid"),
        imgBase64: this.baseStepOne,
        crpValue: this.beforeLable,
        label: this.holeLabel.toString(),
      });
      this.showScreenshotsImg = false;
    },
    unique(arr1) {
      const res = new Map();
      return arr1.filter((a) => !res.has(a.name) && res.set(a.name, 1));
    },
    maxNumber(arry) {
      const max = Math.max(...arry);
      return max;
    },
    minNumber(arry) {
      const min = Math.min(...arry);
      return min;
    },
    handleRemove() {
      this.$refs["rebateUpload"].clearFiles(); //清除文件
      //上传框
      this.isShowUpload = true;
      this.isShowUploadtxt = false;
      //可以计算
      this.computeAllowed = true;
      this.computeLoading = false;
      //上传进度条
      this.percentage = 0;
      //显示进度
      this.isShowPer = false;
      this.originalDataRate = [];
      this.originalData = [];
      this.stepTwoList = [];
      this.isShowStepOne = false;
      this.isShowStepTwo = false;
      this.isShowInputLog = false;
      this.virusLabel = [];
      this.baseStepOne = [];
      this.unit = "μg/ml";
      this.innerControl = ["", ""];
      this.doDownload = false;
      clearStore();
      this.reset();
    },
    downloadExl() {
      if (this.isShowStepTwo && this.doDownload) {
        const lang = getStore("spr-lang") || "zh";
        const href = `${
          process.env.BASE_URL
        }receive/download/excel/1/${lang}/${getStore("vuuid")}`;
        window.open(href, "_blank");
      } else {
        this.$message({
          type: "error",
          message: this.$t("page.doDownload"),
        });
      }
    },
    opens() {
      setTimeout(() => {
        let triggerResize = new Event("resize");
        window.dispatchEvent(triggerResize);
      }, 0);
    },
    findCloseNum(arr, num) {
      var index = 0; // 保存最接近数值在数组中的索引
      var d_value = Number.MAX_VALUE; // 保存差值绝对值，默认为最大数值
      for (var i = 0; i < arr.length; i++) {
        var new_d_value = Math.abs(arr[i] - num); // 新差值
        if (new_d_value <= d_value) {
          // 如果新差值绝对值小于等于旧差值绝对值，保存新差值绝对值和索引
          if (new_d_value === d_value && arr[i] < arr[index]) {
            // 如果数组中两个数值跟目标数值差值一样，取大
            continue;
          }
          index = i;
          d_value = new_d_value;
        }
      }
      return index; // 返回最接近的数值
    },
    drawInnerChart(name) {
      this.innerCharts = [];
      // this.innerControlDiff 展示图形的值
      // console.log(this.innerControlDiff, 'this.innerControlDiff');
      const newInnerControlDiff = this.innerControlDiff;
      for (let i in newInnerControlDiff) {
        let drawWaveChartItem = [];
        // console.log(newInnerControlDiff[i], 'newInnerControlDiff[i]');
        newInnerControlDiff[i].forEach((item, index) => {
          if (this.virusUnitLabel[index]) {
            drawWaveChartItem.push(
              `${this.waveName[index]}[${this.holeLabel[index]}]\n${this.virusUnitLabel[index]}`
            );
          } else {
            drawWaveChartItem.push(this.waveName[index]);
          }
        });

        const innerChart = {
          title: {
            text: i + "(" + this.$t("page.ratioText") + ")",
            left: "center",
          },
          animation: false,
          color: ["#3398DB"],
          tooltip: {
            trigger: "axis",
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          xAxis: {
            type: "category",
            data: drawWaveChartItem,
            axisTick: {
              alignWithLabel: true,
            },
          },
          yAxis: {
            type: "value",
            splitNumber: 6,
            // interval: 0.2
          },
          series: [
            {
              data: newInnerControlDiff[i],
              barWidth: "60%",
              type: "bar",
              // 标示线
              markLine: {
                symbol: ["none", "none"], //去掉箭头
                itemStyle: {
                  normal: {
                    lineStyle: {
                      type: "solid",
                      color: "#F10909",
                    },
                  },
                },
                data: [{ yAxis: this.markLineValue }], //这里设置false是隐藏不了的，可以设置为-1
              },
            },
          ],
        };
        this.innerCharts.push(innerChart);
      }
    },
    drawWaveChart() {
      this.waveCharts = [];
      for (let i in this.waveLengthDiff) {
        let drawWaveChartItem = [];
        this.waveLengthDiff[i].forEach((item, index) => {
          if (this.virusUnitLabel[index]) {
            drawWaveChartItem.push(
              `${this.waveName[index]}[${this.holeLabel[index]}]\n${this.virusUnitLabel[index]}`
            );
          } else {
            drawWaveChartItem.push(this.waveName[index]);
          }
        });

        const waveChart = {
          title: {
            text: i,
            left: "center",
          },
          animation: false,
          color: ["#3398DB"],
          tooltip: {
            trigger: "axis",
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
            },
          },
          xAxis: {
            type: "category",
            data: drawWaveChartItem,
            axisTick: {
              alignWithLabel: true,
            },
          },
          yAxis: {
            type: "value",
            splitNumber: 6,
          },
          series: [
            {
              data: this.waveLengthDiff[i],
              barWidth: "60%",
              type: "bar",
            },
          ],
        };
        this.waveCharts.push(waveChart);
      }
    },
    drawSingleChart() {
      const fistNumber = this.findCloseNum(this.originalWaveLength, 590);
      const lastNumber = this.findCloseNum(this.originalWaveLength, 610);
      this.allwaveLengthDiffSingleCharts = [];
      this.waveLengthDiffSingle.forEach((item, index) => {
        const chartName = this.resultTitle[index];
        let chartsOptionSingle = {
          title: {
            text: "",
            left: "center",
          },
          animation: false,
          tooltip: {
            trigger: "axis",
          },
          color: COLORLIST,
          legend: {
            left: "center",
            top: "75%",
            icon: "circle",
            selectedMode: "single",
            data: [],
          },
          grid: {
            top: "9%",
            left: "3%",
            right: "5%",
            bottom: "40%",
            containLabel: true,
          },
          dataZoom: [
            {
              bottom: "30%",
              type: "slider",
              height: 15,
              handleSize: "140%",
              handleStyle: {
                color: "#999",
              },
              xAxisIndex: 0,
              filterMode: "empty",
            },
            {
              type: "slider",
              yAxisIndex: 0,
              width: 15,
              handleSize: "140%",
              handleStyle: {
                color: "#999",
              },
              filterMode: "empty",
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "category",
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: false,
            minInterval: 120,
            data: [],
          },
          yAxis: {
            type: "value",
            splitNumber: 6,
          },
          series: [],
        };
        chartsOptionSingle.series = [];
        chartsOptionSingle.xAxis.data = [];
        let singleNum = 0;
        for (let i in item) {
          let chartSeries = {};
          if (this.virusUnitLabel[singleNum]) {
            chartSeries = {
              name: `${this.waveName[singleNum]}[${this.holeLabel[singleNum]}]\n${this.virusUnitLabel[singleNum]}`,
              type: "line",
              // smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
              // 每根线的颜色
              lineStyle: {
                width: 2.2,
              },
              markLine: {
                lineStyle: {
                  normal: {
                    color: "#000",
                    type: "dashed",
                  },
                },
                data: [
                  [
                    {
                      coord: [fistNumber, item[i][fistNumber]],
                      symbol: "none",
                    },
                    {
                      coord: [lastNumber, item[i][lastNumber]],
                      symbol: "none",
                    },
                  ],
                ],
              },
            };
            chartsOptionSingle.legend.data.push(
              `${this.waveName[singleNum]}[${this.holeLabel[singleNum]}]\n${this.virusUnitLabel[singleNum]}`
            );
          } else {
            chartSeries = {
              name: this.waveName[singleNum],
              type: "line",
              // smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i],
              // 每根线的颜色
              lineStyle: {
                width: 2.2,
              },
              markLine: {
                lineStyle: {
                  normal: {
                    color: "#000",
                    type: "dashed",
                  },
                },
                data: [
                  [
                    {
                      coord: [fistNumber, item[i][fistNumber]],
                      symbol: "none",
                    },
                    {
                      coord: [lastNumber, item[i][lastNumber]],
                      symbol: "none",
                    },
                  ],
                ],
              },
            };
            chartsOptionSingle.title.text = chartName;
            chartsOptionSingle.legend.data.push(this.waveName[singleNum]);
          }
          chartsOptionSingle.series.push(chartSeries);
          singleNum++;
          chartsOptionSingle.xAxis.data = this.originalWaveLength;
        }
        this.allwaveLengthDiffSingleCharts.push(chartsOptionSingle);
      });
    },
    drawChart() {
      this.allStepOneCharts = [];
      this.originalDataRate.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: "",
            left: "center",
          },
          animation: false,
          tooltip: {
            trigger: "axis",
          },
          color: COLORLIST,
          legend: {
            left: "center",
            top: "75%",
            icon: "circle",
            data: [],
            y: "center",
          },
          grid: {
            top: "9%",
            left: "3%",
            right: "5%",
            bottom: "40%",
            containLabel: true,
          },
          dataZoom: [
            {
              bottom: "30%",
              type: "slider",
              xAxisIndex: 0,
              height: 15,
              handleSize: "140%",
              handleStyle: {
                color: "#999",
              },
              filterMode: "empty",
            },
            {
              type: "slider",
              yAxisIndex: 0,
              width: 15,
              handleSize: "140%",
              handleStyle: {
                color: "#999",
              },
              filterMode: "empty",
            },
          ],
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "category",
            axisTick: {
              alignWithLabel: true,
            },
            boundaryGap: false,
            minInterval: 120,
            data: [],
          },
          yAxis: {
            type: "value",
            splitNumber: 6,
          },
          series: [],
        };
        chartsOption.series = [];
        chartsOption.xAxis.data = [];
        let num = 0;
        for (let i in item) {
          if (i !== "time") {
            let chartSeries = {};
            if (this.virusUnitLabel[num]) {
              chartSeries = {
                name: `${this.waveName[num]}[${this.holeLabel[num]}](${this.virusUnitLabel[num]})`,
                type: "line",
                // smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
              };
              chartsOption.legend.data.push(
                `${this.waveName[num]}[${this.holeLabel[num]}](${this.virusUnitLabel[num]})`
              );
            } else {
              chartSeries = {
                name: this.waveName[num],
                type: "line",
                // smooth: true,
                showSymbol: false,
                hoverAnimation: false,
                data: item[i],
              };
              chartsOption.legend.data.push(this.waveName[num]);
            }

            chartsOption.title.text =
              this.$t("page.ODrate") + this.$t("page.curve");

            chartsOption.series.push(chartSeries);
            num++;
          } else {
            chartsOption.xAxis.data = item[i];
          }
        }
        this.allStepOneCharts.push(chartsOption);
      });

      let _this = this;
      setTimeout(() => {
        _this.showScreenshotsImg = false;
      }, 1500);
    },
    shotImg(data) {
      this.baseStepOne.push(data);
    },
  },
  computed: {
    upload: () => {
      return `${process.env.BASE_URL}receive/pig/upload/step1`;
    },
    headerUpload: () => {
      const data = {};
      data.TOKEN = getToken();
      if (localStorage.getItem("spr-lang") === "en") {
        data.LANG = "ENG"; // 传语言
      }
      return data;
    },
  },
};
</script>

<style lang="scss" scoped>
table {
  border-collapse: collapse;
  text-align: center;
  white-space: nowrap;
  margin-bottom: 20px;
}

.title-space::before {
  content: "*";
  color: red;
  margin-right: 2px;
}
.flex-space {
  justify-content: space-between;
}
.addcontrast-item {
  display: flex;
  align-items: center;
  .label {
    min-width: 30px;
    text-align: center;
  }
  .label-lang {
    padding-right: 10px;
    text-align: center;
  }
  .select-width {
    width: 150px;
  }
  .el-input {
    flex: 2;
  }
  .delete {
    width: 70px;
    margin-left: 10px;
  }
}
.el-form-item {
  margin-bottom: 10px;
  padding-top: 10px;
  border-top: 1px solid #ccc;
}
.el-form-item:first-child {
  border-top: none;
}
.el-form-item:last-child {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}
// .el-form-item:nth-child(even) {
//   background: #fff;
// }
.el-input {
  width: 100px;
  input {
    padding: 0;
  }
}
.reset-back {
  display: flex;
  align-items: center;
  margin: 0 20px 20px;
  .link {
    cursor: pointer;
    color: #409eff;
    font-style: normal;
    margin-right: 20px;
  }
}
.result-light {
  display: flex;
  width: 800px;
  flex-wrap: wrap;
}
.result-item {
  width: 50px;
  text-align: center;
  margin-right: 2px;
  // border: 1px solid #028cdf;
}
</style>
